/**
 * 用户登录与退出模块
 */

const express = require('express')
const router = express.Router()

// 导入数据库
const db = require('../../utils/db')
// 导入加密模块
const getSha1 = require('../../utils/crypo')

// 登录
router.get('/login', (req, res) => {
   res.render('admin/admin_login', {title: '登录'})
})
router.post('/dologin', (req, res) => {
   const {uname, pwd} = req.body
   const sql = `SELECT uname,pwd FROM admin_users WHERE uname='${uname}'`
   db.query(sql, (err, result) => {
      if (err) throw err
      if (result.length > 0) {
         if (result[0].pwd === getSha1(pwd)) {
            req.session.uname = uname
            res.send(`<script>window.location.href='/admin/index'</script>`)
         } else {
            res.send(`<script>alert('用户名密码错误~');window.location.href='/admin/login'</script>`)
         }
      } else {
         res.send(`<script>alert('该用户未注册~');window.location.href='/admin/login'</script>`)
      }
   })
})

// 退出登陆
router.get('/logon', (req, res) => {
   req.session.uname = null // 请求登录记录
   res.redirect('/login')
})

module.exports = router